package com.devframe.srtp.client;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import org.jboss.netty.handler.codec.http.multipart.DiskAttribute;
import org.jboss.netty.handler.codec.http.multipart.DiskFileUpload;
import org.jboss.netty.handler.codec.http.multipart.HttpDataFactory;
import org.jboss.netty.handler.codec.http.multipart.HttpPostRequestEncoder;

import com.devframe.srtp.SRTPConstants;
import com.devframe.srtp.SRTPResult;
import com.devframe.srtp.client.handle.ClientCreateThumbPictureHandler;
import com.devframe.srtp.client.handle.ClientDeleteFileHandler;
import com.devframe.srtp.client.handle.ClientReplaceFileHandler;
import com.devframe.srtp.client.handle.ClientUploadFileHandler;
import com.devframe.srtp.client.handle.ClientWrapFileHandler;
import com.devframe.srtp.client.support.SRTPClientPipelineFactory;

import java.io.File;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.Executors;

public class SRTPClient {
    private static final Log logger = LogFactory.getLog(SRTPClient.class);
    private static URI getUri(String host,int port){
    	  String postUrl = "http://"+host+":"+port+"/formpost";
      	  URI uri;
            try {
            	uri = new URI(postUrl);
                
            } catch (URISyntaxException e) {
                logger.error("Error: " + e.getMessage());
                return null;
            }
            return uri;
    }
    private static ClientBootstrap createClientBootstrap(SRTPClientPipelineFactory clientPipelineFactory){
        ClientBootstrap bootstrap = new ClientBootstrap(
                new NioClientSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));
        bootstrap.setPipelineFactory(clientPipelineFactory);
        // setup the factory: here using a mixed memory/disk based on size threshold
        return bootstrap;
  }
    
    private static HttpDataFactory getHttpDataFactory(){
      HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if size exceed MINSIZE
      DiskFileUpload.deleteOnExitTemporaryFile = false;  
      DiskFileUpload.baseDirectory = System.getProperty("user.dir");  
      DiskAttribute.deleteOnExitTemporaryFile = false; // should delete file on exit (in normal exit)
      DiskAttribute.baseDirectory = System.getProperty("user.dir"); // system temp directory
      return factory;
    }
    private static void uploadFile(ClientBootstrap bootstrap, String host, int port,  File file,String fileName,String thumbMark,String userName,String pwd) {
      	 URI uri=SRTPClient.getUri(host, port);
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        Channel channel = future.awaitUninterruptibly().getChannel();
        if (!future.isSuccess()) {
            future.getCause().printStackTrace();
            bootstrap.releaseExternalResources();
            return;
        }
        ClientWrapFileHandler handler=new ClientUploadFileHandler(host,uri,file,fileName,thumbMark,userName,pwd);
        HttpRequest request =handler.getRequest();
    	HttpDataFactory factory = SRTPClient.getHttpDataFactory();
        HttpPostRequestEncoder bodyRequestEncoder = handler.wrapRequestData(factory);
        channel.write(request);
        if (bodyRequestEncoder.isChunked()) {
            channel.write(bodyRequestEncoder).awaitUninterruptibly();
        }
        bodyRequestEncoder.cleanFiles();
        channel.getCloseFuture().awaitUninterruptibly();
        
        bootstrap.releaseExternalResources();
        factory.cleanAllHttpDatas();
    }
    /**
     * 上传文件
     * @param file
     * @param fileName
     * @param thumbMark：是否需要生成缩略图 true 是，false:否
     * @return
     */
    public static String uploadFile(File file,String fileName,boolean thumbMark){
    	SRTPClientPipelineFactory clientPipelineFactory=new SRTPClientPipelineFactory();
    	ClientBootstrap bootstrap=SRTPClient.createClientBootstrap(clientPipelineFactory);
    	String strThumbMark=SRTPConstants.THUMB_MARK_NO;
    	if(thumbMark){
    		strThumbMark=SRTPConstants.THUMB_MARK_YES;
    	}
    	SRTPClient.uploadFile(bootstrap, SRTPClientContainer.getHost(), SRTPClientContainer.getPort(), file,fileName,strThumbMark,SRTPClientContainer.getUserName(),SRTPClientContainer.getPassword());
    	SRTPResult result=clientPipelineFactory.getResult();
    	if(result!=null && result.isCode()){
    		return result.getFilePath();
    	}
    	return null;
    }
    /**
     * 
     * @param bootstrap
     * @param host
     * @param port
     * @param filePath
     */
    private static void deleteFile(ClientBootstrap bootstrap, String host, int port, String filePath,String userName,String pwd){
    	URI uri=SRTPClient.getUri(host, port);
  	    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        Channel channel = future.awaitUninterruptibly().getChannel();
        if (!future.isSuccess()) {
            future.getCause().printStackTrace();
            bootstrap.releaseExternalResources();
            return;
        }
        
        ClientWrapFileHandler handler=new ClientDeleteFileHandler(host,uri,filePath,userName,pwd);
        HttpRequest request =handler.getRequest();
        HttpDataFactory factory = SRTPClient.getHttpDataFactory();
        HttpPostRequestEncoder bodyRequestEncoder = handler.wrapRequestData(factory);
        channel.write(request);
        if (bodyRequestEncoder.isChunked()) {
            channel.write(bodyRequestEncoder).awaitUninterruptibly();
        }
        bodyRequestEncoder.cleanFiles();
        channel.getCloseFuture().awaitUninterruptibly();
        bootstrap.releaseExternalResources();
        factory.cleanAllHttpDatas();
  }
    /**
     * 删除文件
     * @param filePath，指定要删除的文件路径
     * @return
     */
    public static boolean deleteFile(String filePath,String userName,String pwd){
    	SRTPClientPipelineFactory clientPipelineFactory=new SRTPClientPipelineFactory();
    	ClientBootstrap bootstrap=SRTPClient.createClientBootstrap(clientPipelineFactory);
    	SRTPClient.deleteFile(bootstrap, SRTPClientContainer.getHost(), SRTPClientContainer.getPort(), filePath,userName,pwd);
    	SRTPResult result=clientPipelineFactory.getResult();
    	if(result!=null && result.isCode()){
    		return result.isCode();
    	}
    	return false;
    }
    /**
     * 删除文件
     * @param filePath
     * @return
     * @author:詹保山
     */
    public static boolean deleteFile(String filePath){
    	return  deleteFile(filePath,SRTPClientContainer.getUserName(),SRTPClientContainer.getPassword());
    }
    
    
    private static void replaceFile(ClientBootstrap bootstrap, String host, int port,File file,String filePath,String userName,String pwd) {
    	URI uri=SRTPClient.getUri(host, port);
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        Channel channel = future.awaitUninterruptibly().getChannel();
        if (!future.isSuccess()) {
            future.getCause().printStackTrace();
            bootstrap.releaseExternalResources();
            return;
        }
        
        ClientWrapFileHandler handler=new ClientReplaceFileHandler(host,uri,filePath,file,userName,pwd);
        HttpRequest request =handler.getRequest();
        HttpDataFactory factory = SRTPClient.getHttpDataFactory();
        HttpPostRequestEncoder bodyRequestEncoder = handler.wrapRequestData(factory);
        channel.write(request);
        if (bodyRequestEncoder.isChunked()) {
            channel.write(bodyRequestEncoder).awaitUninterruptibly();
        }
        bodyRequestEncoder.cleanFiles();
        channel.getCloseFuture().awaitUninterruptibly();
        bootstrap.releaseExternalResources();
        factory.cleanAllHttpDatas();
    }
    
    /**
     * 替换文件，但文件指定原来的路径
     * @param file
     * @param filePath
     * @return
     */
    public static boolean replaceFile(File file,String filePath){
    	SRTPClientPipelineFactory clientPipelineFactory=new SRTPClientPipelineFactory();
    	ClientBootstrap bootstrap=SRTPClient.createClientBootstrap(clientPipelineFactory);
    	SRTPClient.replaceFile(bootstrap, SRTPClientContainer.getHost(), SRTPClientContainer.getPort(),file,filePath,SRTPClientContainer.getUserName(),SRTPClientContainer.getPassword());
    	SRTPResult result=clientPipelineFactory.getResult();
    	if(result!=null && result.isCode()){
    		return result.isCode();
    	}
    	
    	return false;
    }
    
    
    /**
     * 
     * @param bootstrap
     * @param host
     * @param port
     * @param filePath
     */
    private static void createThumbPicture(ClientBootstrap bootstrap, String host, int port, String filePath,String userName,String pwd){
    	URI uri=SRTPClient.getUri(host, port);
  	    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        Channel channel = future.awaitUninterruptibly().getChannel();
        if (!future.isSuccess()) {
            future.getCause().printStackTrace();
            bootstrap.releaseExternalResources();
            return;
        }
        
        ClientWrapFileHandler handler=new ClientCreateThumbPictureHandler(host,uri,userName,pwd,filePath);
        HttpRequest request =handler.getRequest();
        HttpDataFactory factory = SRTPClient.getHttpDataFactory();
        HttpPostRequestEncoder bodyRequestEncoder = handler.wrapRequestData(factory);
        channel.write(request);
        if (bodyRequestEncoder.isChunked()) {
            channel.write(bodyRequestEncoder).awaitUninterruptibly();
        }
        bodyRequestEncoder.cleanFiles();
        channel.getCloseFuture().awaitUninterruptibly();
        bootstrap.releaseExternalResources();
        factory.cleanAllHttpDatas();
  }
    /**
     * 文件
     * @param filePath，指定要生成缩略图图片路径
     * @return
     */
    public static boolean createThumbPicture(String filePath,String userName,String pwd){
    	SRTPClientPipelineFactory clientPipelineFactory=new SRTPClientPipelineFactory();
    	ClientBootstrap bootstrap=SRTPClient.createClientBootstrap(clientPipelineFactory);
    	SRTPClient.createThumbPicture(bootstrap, SRTPClientContainer.getHost(), SRTPClientContainer.getPort(), filePath,userName,pwd);
    	SRTPResult result=clientPipelineFactory.getResult();
    	if(result!=null && result.isCode()){
    		return result.isCode();
    	}
    	return false;
    }
    /**
     *  生成缩略图
     * @param filePath 指定要生成缩略图图片路径
     * @return
     * @author:詹保山
     */
    public static boolean createThumbPicture(String filePath){
    	return  createThumbPicture(filePath,SRTPClientContainer.getUserName(),SRTPClientContainer.getPassword());
    }
//
//    public static void main(String[] args) {
//    	  SRTPClient.createThumbPicture( "yt/7/130411134617_8137.jpg");
////      System.out.println(  SRTPClient.uploadFile(new File("D:/4.jpg"), "default_account/3/130406122837_3614.jpg",false));
//    }


    
    
    

   

}
